#include <pthread.h>
#include <unistd.h> // For sleep
#include <semaphore.h>
#include <string.h> // For strlen
#include "Reader.h"
#include "ReaderWriterUtilities.h" // Includes ThreadStruct_t and ReaderWriterManager_t

// Function executed by reader threads
void *readerThread(void *arg) {
    ThreadStruct_t *curThreadStruct = (ThreadStruct_t *)arg;
    ReaderWriterManager_t *rwMgr = curThreadStruct->rwMgr;
    int threadIdx = curThreadStruct->threadIdx;

    printf("Reader %d starting.\n", threadIdx);

    while (rwMgr->exit_flag == 0) { // Check exit flag [Source 25, 57] similar loop structure

        // 读者进入协议
        semWait(&rwMgr->mutex); // 获取保护 read_count 的互斥锁 mutex。
        rwMgr->read_count++;
        if (rwMgr->read_count == 1) {
          //  检查是否是第一个读者。
            semWait(&rwMgr->rw_mutex); // 如果是第一个读者，尝试获取 rw_mutex。阻止任何写者进入临界区
        }
        semSignal(&rwMgr->mutex); // 释放保护 read_count 的互斥锁 mutex。其他读者现在可以进入并增加 read_count
        // --- End Reader Entry Protocol ---


        // --- Critical Section: Reading ---
        printf("Reader %d ENTERED critical section. Reading buffer (length %d): \"%.*s\"\n",
               threadIdx, rwMgr->buffer_len, rwMgr->buffer_len, rwMgr->buffer);
        // Simulate reading time
        sleep(WAIT_TIME_IN_SECOND / 2); // Readers might be faster
        printf("Reader %d EXITING critical section.\n", threadIdx);
        // --- End Critical Section ---


        // --- Reader Exit Protocol ---
        semWait(&rwMgr->mutex); // 再次获取保护 read_count 的互斥锁 mutex
        rwMgr->read_count--;
        if (rwMgr->read_count == 0) {
            // 检查是否是最后一个读者。
            semSignal(&rwMgr->rw_mutex); // 如果是，释放 rw_mutex
        }
        semSignal(&rwMgr->mutex); // 释放保护 read_count 的互斥锁 mutex
        // --- End Reader Exit Protocol ---

        // Simulate time between reads
        sleep(WAIT_TIME_IN_SECOND + (rand() % WAIT_TIME_IN_SECOND));
    }

    printf("Reader %d exiting.\n", threadIdx);
    return NULL; // Changed from 'return arg' as NULL is more conventional
}
